package com.tyk.bookstore.front.product.controller;


import com.tyk.bookstore.front.common.core.model.query.SuggestionQuery;
import com.tyk.bookstore.front.common.core.model.result.R;
import com.tyk.bookstore.front.product.model.entity.BookDo;
import com.tyk.bookstore.front.product.model.entity.BookStatisticDo;
import com.tyk.bookstore.front.product.model.vo.BookVo;
import com.tyk.bookstore.front.product.repository.BookRepository;
import com.tyk.bookstore.front.product.repository.BookStatisticRepository;
import com.tyk.bookstore.front.product.service.BookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author tyk
 * @description 书籍管理
 */
@RequestMapping({"api/product/book"})
@Tag(name = "商品管理/书籍管理", description = "书籍管理")
@RestController
@RequiredArgsConstructor
public class BookController {
    private final BookService bookService;

    private final BookRepository bookRepository;
    private final BookStatisticRepository bookStatisticRepository;

    @GetMapping({"{id}"})
    @Operation(summary = "获取书籍详情", description = "获取书籍详情")
    public R<BookVo> getById(
            @Schema(description = "书籍ID")
            @NotNull @Min(1)
            @PathVariable Long id
    ) {
        return R.ok(bookService.getById(id));
    }

    @GetMapping({"suggest"})
    @Operation(summary = "书籍搜索建议列表", description = "书籍搜索建议列表")
    public R<List<String>> getBookSuggestionList(
            @Validated @ParameterObject SuggestionQuery query
    ) {
        return R.ok(bookService.getSuggestionList(query));
    }


    @GetMapping({"copy/{id}/{num}"})
    @Operation(summary = "书籍数据复制", description = "书籍数据复制(仅用于复制书籍数据)")
    public R<Object> copy(
            @PathVariable Long id,
            @PathVariable Long num
    ) {
        BookDo bookDo = bookRepository.selectById(id);
        BookStatisticDo bookStatisticDo = bookStatisticRepository.selectById(id);
        while (num-- != 0) {
            bookDo.setId(null);
            bookRepository.insert(bookDo);
            bookStatisticDo.setBookId(bookDo.getId());
            bookStatisticRepository.insert(bookStatisticDo);
        }
        return R.ok();
    }
}
